package com.smartstate.EnvironmentMonitor.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smartstate.EnvironmentMonitor.controller.TestController;
import com.smartstate.EnvironmentMonitor.dto.ObjMoudelDTO;
import com.smartstate.EnvironmentMonitor.dto.PageDTO;
import com.smartstate.EnvironmentMonitor.dto.common.TreeNode;
import com.smartstate.EnvironmentMonitor.entity.ObjMoudel;
import com.smartstate.EnvironmentMonitor.mapper.ObjMoudelMapper;
import com.smartstate.EnvironmentMonitor.service.ObjMoudelService;
import com.smartstate.EnvironmentMonitor.util.ObjDemoUtils;
import com.smartstate.EnvironmentMonitor.vo.EquipmentForTreeVO;
import com.smartstate.EnvironmentMonitor.vo.ObjmiddleVo;
import com.smartstate.EnvironmentMonitor.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * <p>楼宇</p>
 * <p>@Author 陈永杰</p>
 * <p>@Date: 2022/8/17</p>
 * <p>@Time: 22:06</p>
 * <p>@version 1.0 <p>
 */
@Transactional
@Service
@Slf4j
public class ObjMoudelServiceImpl extends ServiceImpl<ObjMoudelMapper, ObjMoudel> implements ObjMoudelService {

    @Resource
    private ObjMoudelMapper objMoudelMapper;

    @Value("${environmental.monitoring}")
    private String url;

    @Override
    public Page<ObjMoudel> queryAllPageByDTO(PageDTO pageDTO) {
        return null;
    }

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 楼宇树结构
     * @return
     */
    @Override
    public List<TreeNode> selectMoudel(String type) {
        List<TreeNode> nodeList= objMoudelMapper.selectModelTree(type);
        List<EquipmentForTreeVO> equipmentList = objMoudelMapper.selectTree();
        for (EquipmentForTreeVO equipmentForTreeVO : equipmentList) {
            if (equipmentForTreeVO.getDeviceId()!=null && !"".equals(equipmentForTreeVO.getDeviceId())){
                //TODO IOT推上来的数据格式未定
                String types = (String) redisTemplate.opsForHash().get(equipmentForTreeVO.getDeviceId(), "type");
                equipmentForTreeVO.setTypes(types);
            }
        }
        return ObjDemoUtils.getTreeNode(nodeList,equipmentList);
    }

    @Override
    public int updatePhoto(@RequestParam(value = "file", required = false) MultipartFile file, ObjMoudel objMoudel) {
        TestController ts = new TestController();
        ResultVO resultVO = ts.uploadImage(file, url);
        objMoudel.setCreateTime(new Date());
        objMoudel.setPhoto(url+resultVO.getData());
        return objMoudelMapper.updatePhoto(objMoudel.getId(),objMoudel.getPhoto());
    }

    @Override
    public int updateMetering(String id, String metering) {
        return objMoudelMapper.updateMetering(id,metering);
    }


    /**
     * 添加设备 和楼宇 中间表
     * @param
     */
    @Override
    public int addObjmiddle(ObjmiddleVo objmiddleVo) {
        return objMoudelMapper.addObjmiddle(objmiddleVo);
    }


    /**
     * 新增节点或修改节点 id=0新建根节点，id!=0修改或添加子节点
     * @param
     */
    @Override
    public boolean addOrUpdateNode(ObjMoudelDTO objMoudelDTO) {
        ObjMoudel objMoudel = new ObjMoudel();
//        objMoudelDTO对于属性赋值到objMoudel
        BeanUtils.copyProperties(objMoudelDTO, objMoudel);
////        修改节点
        if(objMoudel.getType() == null)
            return objMoudelMapper.updateById(objMoudel) > 0;
//        添加根节点
        if ("0".equals(objMoudel.getId())) {
            if (objMoudelMapper.queryType(objMoudelDTO.getType()).size() > 0)
                return false;
        }
        objMoudel.setCreateTime(new Date());
        objMoudel.setParentId(objMoudelDTO.getId());
        objMoudel.setId(UUID.randomUUID().toString());
        objMoudel.setUpdateTime(new Date());
        return  objMoudelMapper.insert(objMoudel) > 0;
    }
    /**
     * 根据list中的节点id集合删除对于节点
     * @param list
     * @return
     */
    @Override
    public boolean delectNode(List<String> list) {
        AtomicBoolean flag = new AtomicBoolean(false);
        list.forEach((s) -> {
            flag.set(delectByQueryId(s));
        });
        return flag.get();
    }

    /**
     * 递归删除该id对应的子节点
     *
     * @param id
     * @return
     */
    public boolean delectByQueryId(String id) {
        List<String> ids = objMoudelMapper.queryId(id);
//        删除图片
        String imgPath = objMoudelMapper.queryImage(id);
        if (imgPath != null){
            delectImage(imgPath);
        }
        objMoudelMapper.deleteById(id);
        objMoudelMapper.deleteObjmiddleById(id);
        if (ids == null || ids.size() == 0) {
            return true;
        }
        ids.forEach((s) -> {
            delectByQueryId(s);
        });
        return true;
    }

    /**
     * 删除节点对应图片
     * @param imgPath
     * @return
     */
    public void delectImage(String imgPath){
//        String path = url.substring(17);
        String path = "F:\\新建文件夹";
        imgPath = path + imgPath;
        File file = new File(imgPath);
        //判断文件是否存在
        if (file.exists() == true){
            log.info(file.delete() == true ? "图片删除成功" : "图片删除失败");
        }else {
            log.info("图片不存在");
        }
    }



}